<template>
    <div class="app-container">
        <div class="pageTitle">
            <div class="pageBtn" style="padding-left: 0;">
                <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd({dept_id:undefined})">添加</el-button>
            </div>
        </div>

        <page-main>
            <el-table
                v-loading="isLoading"
                :data="deptList"
                border
                row-key="dept_id"
                default-expand-all
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :row-class-name="tableRowClassName">
                <el-table-column prop="dept_name" label="组织名称" width="260" />

                <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)">
                            修改
                        </el-button>
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-plus"
                            @click="handleAdd(scope.row)">
                            新增
                        </el-button>
                        <el-button
                            v-if="scope.row.parent_id != 0"
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </page-main>

        <el-dialog :title="currentDept.isNew?'添加组织':'修改组织'" :visible.sync="detailVisible" width="500px">
            <el-form ref="form" :model="currentDept" :rules="rules" label-width="80px" size="small">
                <el-row>
                    <el-form-item label="上级组织">
                        <treeselect v-if="currentDept.isNew" v-model="currentDept.dept_id" :clearable="false" :options="deptList" :normalizer="normalizer" placeholder="选择上级部门" @select="orgSelected"/>
                        <span v-else style="font-weight: bold;">{{ currentDept.dept_name }}</span>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="名称" prop="dept_name">
                        <el-input v-model="currentDept.dept_name" placeholder="请输入名称" />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="编号" prop="dept_code">
                        <el-input v-model="currentDept.dept_code" placeholder="请输入编号" />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="排序" prop="sorted_no">
                        <el-input-number v-model="currentDept.sorted_no" />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="属性" prop="type">
                        <dict-select v-model="currentDept.dept_type" dict="dict_OrgType" :clearable="false" />
                    </el-form-item>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="detailVisible = false">取 消</el-button>
                <el-button size="small" :loading="isLoading" type="primary" @click="handleSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import moment from 'moment';
    import { handleTree } from '@/util';
    import Treeselect from '@riophae/vue-treeselect';
    import '@riophae/vue-treeselect/dist/vue-treeselect.css';
    import DictSelect from '@/modules/components/DictSelect';

    import {SelectAllTcontrolUnit, QueryOrganization, InsertOrganization, UpdateOrganization, DeleteOrganization} from '@/api/resourceManageApi';

    export default {
        name: 'organization',
        components: {
            Treeselect,
            DictSelect
        },
        props: {},
        data() {
            return {
                deptList: [],
                isLoading: false,
                tableData: [],
                detailVisible: false,
                currentDept: {},
                rules: {
                    dept_name: [
                        { required: true, message: '名称不能为空', trigger: 'blur' }
                    ],
                    dept_code: [
                        { required: true, message: '编号不能为空', trigger: 'blur' }
                    ],
                    sorted_no: [
                        { required: true, message: '排序不能为空', trigger: 'blur' }
                    ]

                }
            };
        },
        created() {

        },
        mounted() {
            this.loadRemoteData();
        },
        methods: {
            moment,
            tableRowClassName({row, rowIndex}) {
                if (this.detailVisible && this.currentDept.dept_id == row.dept_id) {
                    return 'selected-row';
                }
                return '';
            },
            loadRemoteData() {
                this.isLoading = true;
                SelectAllTcontrolUnit().then(res => {
                    this.isLoading = false;
                    console.log(res);
                    let list = res.res.Dept;
                    list[0].parent_id = 0;
                    this.deptList = handleTree(list, 'dept_id', 'parent_id', 'children', 0);
                    // this.deptList = handleTree(list, 'control_unit_id', 'parent_id', 'children', 0);
                    console.log("----------------------");
                    console.log(this.deptList);

                }).catch(err => {
                    this.isLoading = false;
                    console.log(err);
                });
            },
            normalizer(node) {
                if (node.children && !node.children.length) {
                    delete node.children;
                }
                return {
                    isDefaultExpanded: true,
                    id: node.dept_id,
                    label: node.dept_name,
                    children: node.children
                };
            },
            orgSelected(node) {
                this.currentDept.parent_id = node.dept_id;
            },
            handleDelete(item) {

                if (item.children && item.children.length > 0) {
                    this.$message.error('本节点不是末节节点，不允许删除');
                    return;
                }

                this.$confirm('是否确认删除名称为"' + item.dept_name + '"的数据项?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    this.isLoading = true;
                    DeleteOrganization({
                        dept_id: item.dept_id
                    }).then(res => {
                        this.isLoading = false;
                        this.$message.success('删除成功');
                        this.loadRemoteData();
                    }).catch(err => {
                        this.isLoading = false;
                        console.log(err);
                    });

                }).catch(err => {
                    console.log(err);
                });
            },
            handleUpdate(item) {
                this.isLoading = true;
                QueryOrganization({
                    dept_id: item.dept_id
                }).then(res => {
                    this.isLoading = false;
                    this.currentDept = res.res.QueryOrganization && res.res.QueryOrganization[0];
                    this.currentDept.dept_id = item.dept_id;

                    this.detailVisible = true;
                    this.$nextTick(() => {
                        this.$refs['form'] && this.$refs['form'].clearValidate();
                    });
                }).catch(err => {
                    this.isLoading = false;
                    console.log(err);
                });

                // this.currentDept = {...item};
                // this.detailVisible = true;
            },
            handleAdd(item) {
                this.currentDept = {
                    isNew: true,
                    dept_id: item.dept_id,
                    Level: 1,
                    type: 0
                };
                this.detailVisible = true;
                this.$nextTick(() => {
                    this.$refs['form'] && this.$refs['form'].clearValidate();
                });
            },
            handleSubmit() {
                if (this.clickTooFast()) return;

                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.isLoading = true;
                        console.log("----------------");
                        console.log(this.currentDept);
                        if (this.currentDept.isNew) {
                            InsertOrganization(this.currentDept).then(res => {
                                this.$message.success('添加成功');
                                this.loadRemoteData();
                                this.detailVisible = false;
                                this.isLoading = false;
                            }).catch(err => {
                                this.isLoading = false;
                                console.log(err);
                            });
                        } else {
                            UpdateOrganization(this.currentDept).then(res => {
                                this.$message.success('修改成功');
                                this.loadRemoteData();
                                this.detailVisible = false;
                                this.isLoading = false;
                            }).catch(err => {
                                this.isLoading = false;
                                console.log(err);
                            });
                        }
                    }
                });

            }
        }
    };
</script>

<style scoped>

.table-header {
    background-color: #f8f8f8 !important;
}
/deep/
.el-table td {
    padding: 5px 0 !important;
}
/deep/
.el-button--text {
    padding: 5px 0;
}
</style>
